const TIME_INDEX = 0;
const ROOMID_INDEX = 1;
const VIDEO_INDEX = 12;
const SECOND_INDEX = 4;
const RESOLUTION_INDEX = 6;
const APPID = 886286150;
let excelresult = [];
let questionStr = '';
let roomIdData = {};
let headers = [];
let videoUrlArray = [];
let startTimeIndex=0
// 缓存token
const url = new URL(window.location.href);
const urlSearch = url.search;
if (urlSearch && urlSearch.indexOf('business') > -1) {
  localStorage.setItem('lg_video_token', urlSearch);
}
// 获取缓存的token
const lg_video_token = localStorage.getItem('lg_video_token');


let classTime, startTime, endTime, appid, roomid, timeBegin, timeEnd, pullUser;


let paths = {
  title: '', //标题
  videoPath: '',
  recordPath: '', //生成查录制时间的链接
  pusherStatePath: '', // room and pusherState
  playerStatePath: '', // room and playState
  deviceChangePath: '', // room and deviceChange
  starMapPath: '', // 星图
  topologyPath: '', // 流拓扑
  pusherOrRefreshPath: '', // 推流 & 刷新 针对推流异常，刷新解决
  pusherOrRefresh: [], //结果
  playerOrRefreshPath: '', // 拉流 & 刷新 针对拉流异常，刷新解决
  playerOrRefresh: [],
  mediaNodePath: '', // 媒体节点连接
  udpPath: '', // UDP链接
  switchDevicePath: '',
  logAnlyzeToolPath: '',
  speedlogsToolPath: '',
};

/**
 * 点击“生成按钮连接”
 */
function onGeneratePath() {
  let question = questionStr ? questionStr.split('\t') : document.querySelector('textarea').value.split('\t');
  console.log("question",question)
  //new Date("2023-7-26 22:00").getTime() - (30 * 60 * 1000)
  classTime = new Date(question[startTimeIndex].split(',').join('')).getTime();
  startTime = new Date(classTime - (30 * 60 * 1000)).toISOString(); // 课堂开始时间提前半小时
  endTime = new Date(classTime + (90 * 60 * 1000)).toISOString(); // 课堂开始时间延后1.5小时
  appid = APPID;
  roomid = question[ROOMID_INDEX].split(',').join('');
  timeBegin = classTime;
  timeEnd = new Date(classTime + (90 * 60 * 1000)).getTime();
  // 置空数据
  videoUrlArray = [];
  document.getElementById("videoPathBox").innerHTML = ""
  paths.title = genenrateTitle(question);
  paths.videoPath = genenrateVideoPath(question);
  paths.recordPath = generateRecordPath(startTime, endTime, appid, roomid);
  paths.pusherStatePath = generatePusherStatePath(startTime, endTime, appid, roomid);
  paths.playerStatePath = generatePlayerStatePath(startTime, endTime, appid, roomid);
  paths.deviceChangePath = generateDeviceChangePath(startTime, endTime, appid, roomid);
  paths.starMapPath = generateStarMapPath(appid, roomid, timeBegin, timeEnd);
  paths.pusherOrRefreshPath = generatePusherOrRefresh(startTime, endTime, appid, roomid);
  paths.playerOrRefreshPath = generatePlayerOrRefresh(startTime, endTime, appid, roomid);
  paths.switchDevicePath = generateSwitchDevicePath(startTime, endTime, appid, roomid);
  paths.logAnlyzeToolPath = generateLogAnlyzeToolPath(startTime, endTime, appid, roomid);
  paths.speedlogsToolPath = generateSpeedlogrStatePath(startTime, endTime, appid, roomid);
  // generateTopologyPath()

  console.log('[onGeneratePath]', paths);
  render(paths);
}

function onGenerateMediaNodePath() {
  const streamID = document.querySelector('#mediaNodePath_textArea').value;
  paths.mediaNodePath = generateMediaNodePath(startTime, endTime, appid, roomid, streamID);
  document.querySelector('#mediaNodePath').value = paths.mediaNodePath;
  document.querySelector('#mediaNodePath_link').setAttribute('href', paths.mediaNodePath);
  console.log('[onGenerateMediaNodePath]', paths);
}

/**
 * 点击“生成 Boss 流链路 的链接”按钮
 */
function onGeneratePullStreamPath() {
  let topologyArea = document.querySelector('#topologyPath_textArea').value.split('+');
  const streamID = topologyArea[0];
  pullUser = topologyArea[1];
  paths.topologyPath = generateTopologyPath(appid, streamID, timeBegin, timeEnd, pullUser);

  document.querySelector('#topologyPath').value = paths.topologyPath;
  document.querySelector('#topologyPath_link').setAttribute('href', paths.topologyPath);
  console.log('[onGeneratePullStreamPath]', paths);
}

function onGenerateUDPPath() {
  const streamID = document.querySelector('#udpPath_textArea').value;
  paths.udpPath = generateUDPPath(startTime, endTime, appid, streamID);
  document.querySelector('#udpPath').value = paths.udpPath;
  document.querySelector('#udpPath_link').setAttribute('href', paths.udpPath);
  console.log('[onGenerateUDPPath]', paths);
}

function render(paths) {
  const $title = document.querySelector('.paths h2');
  $title.innerHTML = paths.title;
  // if(videoUrlArray.length==1){
  //   document.querySelector('#videoPath').value = paths.videoPath;
  //   document.querySelector('#videoPath_link').setAttribute('href', paths.videoPath);
  // }else{
  //   document.querySelector('#videoPath').value = paths.videoPath;
  //   document.querySelector('#videoPath_link').setAttribute('href', paths.videoPath);
  // }
  console.log(videoUrlArray.length)

  videoUrlArray.forEach((url, index) => {
    if (url != "") {
      const aTag = document.createElement('a');
      aTag.href = url + lg_video_token;
      aTag.target = '_blank';
      aTag.innerText = '视频链接' + index + ",";
      document.getElementById("videoPathBox").appendChild(aTag);
    }
  });

  document.querySelector('#recordPath').value = paths.recordPath;
  document.querySelector('#recordPath_link').setAttribute('href', paths.recordPath);

  document.querySelector('#pusherStatePath').value = paths.pusherStatePath;
  document.querySelector('#pusherStatePath_link').setAttribute('href', paths.pusherStatePath);

  document.querySelector('#playerStatePath').value = paths.playerStatePath;
  document.querySelector('#playerStatePath_link').setAttribute('href', paths.playerStatePath);

  document.querySelector('#deviceChangePath').value = paths.deviceChangePath;
  document.querySelector('#deviceChangePath_link').setAttribute('href', paths.deviceChangePath);

  document.querySelector('#starMapPath').value = paths.starMapPath;
  document.querySelector('#starMapPath_link').setAttribute('href', paths.starMapPath);

  document.querySelector('#switchDevicePath').value = paths.switchDevicePath;
  document.querySelector('#switchDevicePath_link').setAttribute('href', paths.switchDevicePath);

  document.querySelector('#logAnalyzeToolPath').value = paths.logAnlyzeToolPath;
  document.querySelector('#logAnalyzeToolPath_link').setAttribute('href', paths.logAnlyzeToolPath);

  document.querySelector('#speedlogsPath').value = paths.speedlogsToolPath;
  document.querySelector('#speedlogsPath_link').setAttribute('href', paths.speedlogsToolPath);
  document.querySelector('#pusherOrRefresh_link').setAttribute('href', paths.pusherOrRefreshPath);
  document.querySelector('#playerOrRefresh_link').setAttribute('href', paths.playerOrRefreshPath);


}

function genenrateTitle(question) {
  return question[SECOND_INDEX] + ', ' + question[RESOLUTION_INDEX];
}

function genenrateVideoPath(question) {
  if (question) {
    videoUrlArray = question[VIDEO_INDEX].split(/,/);
    if (videoUrlArray.length == 1 && videoUrlArray[0] != "") {
      return videoUrlArray[0] + lg_video_token;
    } else {
      return question[VIDEO_INDEX] + lg_video_token;
    }
  }
}

/**
 * 生成查录制时间的链接
 * @param {*} startTime 2023-07-17T16:00:00.000Z
 * @param {*} endTime 2023-07-18T15:30:00.000Z
 * @param {*} appid 886286150
 * @param {*} roomid 4247279
 * @returns 
 */
function generateRecordPath(startTime, endTime, appid, roomid) {
  return `https://logcenter-new.zego.cloud/app/discover#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:'${startTime}',to:'${endTime}'))&_a=(columns:!(app_id,operate,task_id,room_id,origin_req),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:a1465460-f021-11eb-b67b-a151f09c199f,key:app_id,negate:!f,params:(query:${appid}),type:phrase),query:(match_phrase:(app_id:${appid}))),('$state':(store:appState),meta:(alias:!n,disabled:!f,index:a1465460-f021-11eb-b67b-a151f09c199f,key:operate,negate:!f,params:(query:%2Fstart),type:phrase),query:(match_phrase:(operate:%2Fstart)))),index:a1465460-f021-11eb-b67b-a151f09c199f,interval:auto,query:(language:lucene,query:'room_id:%22${roomid}%22'),sort:!(!('@timestamp',desc)))`;
}
// document.body.textContent = generateRecordPath(new Date('2023-7-26 21:30').toISOString(), new Date('2023-7-26 23:30').toISOString(), 886286150, '4338922')

// document.body.textContent = generateRecordPath('2023-07-17T16:00:00.000Z', '2023-07-18T15:30:00.000Z', 886286150, '4247279')

/**
 * 生成pusher state链接
 * @param {*} startTime 
 * @param {*} endTime 
 * @param {*} appid 
 * @param {*} roomid 
 * @returns 
 */
function generatePusherStatePath(startTime, endTime, appid, roomid) {
  return `https://logcenter-new.zego.cloud/app/discover#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:'${startTime}',to:'${endTime}'))&_a=(columns:!(action,content,event,userid,client_time,action_detail,client_ip,ipip.country_name),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'4f890960-f021-11eb-b67b-a151f09c199f',key:roomid,negate:!f,params:(query:'${roomid}'),type:phrase),query:(match_phrase:(roomid:'${roomid}'))),('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'4f890960-f021-11eb-b67b-a151f09c199f',key:appid,negate:!f,params:(query:${appid}),type:phrase),query:(match_phrase:(appid:${appid})))),index:'4f890960-f021-11eb-b67b-a151f09c199f',interval:auto,query:(language:lucene,query:'%22zm.al%22%20OR%20%22publisherStateUpdate%22%20OR%20%22unload%22%20OR%20%22%E9%A2%84%E8%A7%88%22%20OR%20%22zc.hcqr.0%22%20OR%20(%22zc.s.sss%22%20AND%20NOT%20%22call%22)'),sort:!(!('@timestamp',asc)))`;
}

// document.body.textContent = generatePusherStatePath('2023-07-17T16:00:00.000Z', '2023-07-18T15:30:00.000Z', 886286150, '4247279')

/**
 * 生成player state链接
 * @param {*} startTime 
 * @param {*} endTime 
 * @param {*} appid 
 * @param {*} roomid 
 * @returns 
 */
function generatePlayerStatePath(startTime, endTime, appid, roomid) {
  return `https://logcenter-new.zego.cloud/app/discover#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:'${startTime}',to:'${endTime}'))&_a=(columns:!(action,content,event,userid,client_time,action_detail,client_ip,ipip.country_name),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'4f890960-f021-11eb-b67b-a151f09c199f',key:roomid,negate:!f,params:(query:'${roomid}'),type:phrase),query:(match_phrase:(roomid:'${roomid}'))),('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'4f890960-f021-11eb-b67b-a151f09c199f',key:appid,negate:!f,params:(query:${appid}),type:phrase),query:(match_phrase:(appid:${appid})))),index:'4f890960-f021-11eb-b67b-a151f09c199f',interval:auto,query:(language:lucene,query:'%22zm.al%22%20OR%20%22playerStateUpdate%22%20OR%20%22unload%22%20OR%20%22zc.hcqr.0%22%20OR%20(%22zc.p.orss.1%22%20AND%20NOT%20%22call%22)'),sort:!(!('@timestamp',asc)))`;
}
/**
 * 生成player state链接
 * @param {*} startTime 
 * @param {*} endTime 
 * @param {*} appid 
 * @param {*} roomid 
 * @returns 
 */
function generateSpeedlogrStatePath(startTime, endTime, appid, roomid) {

  return `https://logcenter-new.zego.cloud/app/discover#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:'${startTime}',to:'${endTime}'))&_a=(columns:!(event,error,room_id,id_name,appid,ipip.country_name),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:a0527f80-f016-11eb-b67b-a151f09c199f,key:room_id,negate:!f,params:(query:'${roomid}'),type:phrase),query:(match_phrase:(room_id:'${roomid}'))),('$state':(store:appState),meta:(alias:!n,disabled:!f,index:a0527f80-f016-11eb-b67b-a151f09c199f,key:appid,negate:!f,params:(query:${appid}),type:phrase),query:(match_phrase:(appid:${appid})))),index:a0527f80-f016-11eb-b67b-a151f09c199f,interval:auto,query:(language:lucene,query:''),sort:!(!('@timestamp',asc)))`;
}

// document.body.textContent = generatePlayerStatePath('2023-07-17T16:00:00.000Z', '2023-07-18T15:30:00.000Z', 886286150, '4247279')

/**
 * 生成 设备 & 设备切换 & 推流设备状态 连接
 * @param {*} startTime 
 * @param {*} endTime 
 * @param {*} appid 
 * @param {*} roomid 
 * @returns 
 */
function generateDeviceChangePath(startTime, endTime, appid, roomid) {
  return `https://logcenter-new.zego.cloud/app/discover#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:'${startTime}',to:'${endTime}'))&_a=(columns:!(action,content,event,userid,client_time,action_detail,client_ip),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'4f890960-f021-11eb-b67b-a151f09c199f',key:roomid,negate:!f,params:(query:'${roomid}'),type:phrase),query:(match_phrase:(roomid:'${roomid}'))),('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'4f890960-f021-11eb-b67b-a151f09c199f',key:appid,negate:!f,params:(query:${appid}),type:phrase),query:(match_phrase:(appid:${appid})))),index:'4f890960-f021-11eb-b67b-a151f09c199f',interval:auto,query:(language:lucene,query:'%22zm.al%22%20OR%20%22publisherStateUpdate%22%20OR%20%22unload%22%20OR%20%22%E9%A2%84%E8%A7%88%22%20OR%20%22device%22'),sort:!(!('@timestamp',asc)))`;
}

// document.body.textContent = generateAudioDeviceChangePath('2023-07-17T16:00:00.000Z', '2023-07-18T15:30:00.000Z', 886286150, '4247279')

/**
 * 生成流拓扑连接
 * @param {*} appid 
 * @param {*} streamID 
 * @param {*} timeBegin 
 * @param {*} timeEnd 
 * @param {*} pullUser 
 * @returns 
 */
function generateTopologyPath(appid, streamID, timeBegin, timeEnd, pullUser) {
  return `https://boss.zego.cloud/qualityOperate/fullLinkQuality?appId=${appid}&streamId=${streamID}&timeBegin=${timeBegin}&timeEnd=${timeEnd}&pullUserId=${pullUser}&refreshNow=true`;
}

// document.body.textContent = generateTopologyPath(886286150, '4338922_9586698', new Date('2023-07-26T13:00:00.000Z').getTime(), new Date('2023-07-26T15:30:00.000Z').getTime(), '7856759');

/**
 * 生成星图连接
 * @param {*} appid 
 * @param {*} roomid 
 * @param {*} timeBegin 
 * @param {*} timeEnd 
 * @returns 
 */
function generateStarMapPath(appid, roomid, timeBegin, timeEnd) {
  return `https://prism.zego.im/callInsight/search?app_id=${appid}&app_name=Lingoace%E7%9B%B4%E6%92%AD%E6%95%99%E5%AE%A4&room_id=${roomid}&user_id=&stream_id=&start_time=${timeBegin}&end_time=${timeEnd}&page=1&page_size=200&filter_error=false&no_room=false&stateName=callInsightUrl&searchText=${appid}&hasSelet=%5B%7B%22selectID%22%3A1,%22idValue%22%3A%22${roomid}%22,%22homeId%22%3A%5B%7B%22label%22%3A%22%E6%8E%A8%E6%B5%81%E6%88%BF%E9%97%B4ID%22,%22value%22%3A1%7D,%7B%22label%22%3A%22%E7%94%A8%E6%88%B7ID%22,%22value%22%3A2%7D,%7B%22label%22%3A%22%E6%B5%81ID%22,%22value%22%3A3%7D%5D%7D%5D&utc=8`;
}

// document.body.textContent = generateStarMapPath(886286150, '4338922', new Date('2023-07-26T13:00:00.000Z').getTime(), new Date('2023-07-26T15:30:00.000Z').getTime());

/**
 * 生成推流 & 刷新；针对推流异常，刷新解决
 * @param {*} startTime 
 * @param {*} endTime 
 * @param {*} appid 
 * @param {*} roomid 
 * @returns 
 */
function generatePusherOrRefresh(startTime, endTime, appid, roomid) {
  return `https://logcenter-new.zego.cloud/app/discover#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:'${startTime}',to:'${endTime}'))&_a=(columns:!(action,content,event,userid,client_time,action_detail,client_ip),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'4f890960-f021-11eb-b67b-a151f09c199f',key:roomid,negate:!f,params:(query:'${roomid}'),type:phrase),query:(match_phrase:(roomid:'${roomid}'))),('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'4f890960-f021-11eb-b67b-a151f09c199f',key:appid,negate:!f,params:(query:${appid}),type:phrase),query:(match_phrase:(appid:${appid})))),index:'4f890960-f021-11eb-b67b-a151f09c199f',interval:auto,query:(language:lucene,query:'%22unload%22%20OR%20%22NO_PUBLISH%22%20OR%20%22PUBLISH_REQUESTING%22'),sort:!(!('@timestamp',asc)))`
}

/**
 * 生成拉流 & 刷新； 针对拉流异常，刷新解决
 * @param {*} startTime 
 * @param {*} endTime 
 * @param {*} appid 
 * @param {*} roomid 
 * @returns 
 */
function generatePlayerOrRefresh(startTime, endTime, appid, roomid) {
  return `https://logcenter-new.zego.cloud/app/discover#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:'${startTime}',to:'${endTime}'))&_a=(columns:!(action,content,event,userid,client_time,action_detail,client_ip),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'4f890960-f021-11eb-b67b-a151f09c199f',key:roomid,negate:!f,params:(query:'${roomid}'),type:phrase),query:(match_phrase:(roomid:'${roomid}'))),('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'4f890960-f021-11eb-b67b-a151f09c199f',key:appid,negate:!f,params:(query:${appid}),type:phrase),query:(match_phrase:(appid:${appid})))),index:'4f890960-f021-11eb-b67b-a151f09c199f',interval:auto,query:(language:lucene,query:'%22unload%22%20OR%20%22PLAY_REQUESTING%22%20OR%20%22NO_PLAY%22'),sort:!(!('@timestamp',asc)))`;
}

function generateLogAnlyzeToolPath(startTime, endTime, appid, roomid) {
  const logAnlyzeToolBase = 'https://web-demo-log-template.zegotech.cn/#/';
  return `${logAnlyzeToolBase}?appid=${appid}&roomid=${roomid}&startTime=${new Date(startTime).getTime()}&endTime=${new Date(endTime).getTime()}`;
}

// 从日志异常时间计算视频异常时间 推流异常 & 刷新解决
function calcVideoTimeFromLogByPusherOrRefresh() {
  let area = document.querySelector('#pusherOrRefresh_area').value.split('从日志异常时间计算视频异常时间(针对推流异常，刷新解决)');
  const recordTime = new Date(area[0]).getTime();
  const data = JSON.parse(area[1]);
  data.hits.hits.forEach(hit => {
    // let gap = hit._source.server_time - recordTime; // 用服务端时间计算，有偏差
    let gap = new Date(hit._source.time) - recordTime; // 用客户端时间计算
    if (gap > 0) {
      console.log(formatSeconds(gap / 1000) + ' ~ ' + hit._source.time);
      paths.pusherOrRefresh.push(formatSeconds(gap / 1000) + ' ~ ' + hit._source.time);
    } else {
      paths.pusherOrRefresh.push(0);
    }
  });

  // document.querySelector('#pusherOrRefresh_video').value = [...new Set(paths.pusherOrRefresh)].join(';\n');
  document.querySelector('#pusherOrRefresh_video').innerHTML = [...new Set(paths.pusherOrRefresh)].map(item => {
    return `<span>${item}</span>`
  }).join('<br>');
}

// 从视频异常时间计算日志异常时间
function calcVideoTimeFromLogByPlayerOrRefresh() {
  let area = document.querySelector('#playerOrRefresh_area').value.split('从日志异常时间计算视频异常时间(针对拉流异常，刷新解决)');
  const recordTime = new Date(area[0]).getTime();
  const data = JSON.parse(area[1]);
  data.hits.hits.forEach(hit => {
    // let gap = hit._source.server_time - recordTime;
    let gap = new Date(hit._source.time) - recordTime;
    if (gap > 0) {
      paths.playerOrRefresh.push(formatSeconds(gap / 1000) + ' ~ ' + hit._source.time);
    } else {
      paths.playerOrRefresh.push(0);
    }
  });
  // document.querySelector('#playerOrRefresh_video').value = [...new Set(paths.playerOrRefresh)].join(';');
  document.querySelector('#playerOrRefresh_video').value = [...new Set(paths.playerOrRefresh)].map(item => {
    return `<span>${item}</span>`
  }).join('<br>');
}

//秒数转化为时分秒
function formatSeconds(value) {
  var secondTime = parseInt(value); // 秒
  var minuteTime = 0; // 分
  var hourTime = 0; // 小时
  if (secondTime > 60) { //如果秒数大于60，将秒数转换成整数
    //获取分钟，除以60取整数，得到整数分钟
    minuteTime = parseInt(secondTime / 60);
    //获取秒数，秒数取余，得到整数秒数
    secondTime = parseInt(secondTime % 60);
    //如果分钟大于60，将分钟转换成小时
    if (minuteTime > 60) {
      //获取小时，获取分钟除以60，得到整数小时
      hourTime = parseInt(minuteTime / 60);
      //获取小时后取余的分，获取分钟除以60取余的分
      minuteTime = parseInt(minuteTime % 60);
    }
  }
  var result = "" + parseInt(secondTime) + "秒";

  if (minuteTime > 0) {
    result = "" + parseInt(minuteTime) + "分" + result;
  }
  if (hourTime > 0) {
    result = "" + parseInt(hourTime) + "小时" + result;
  }
  console.log('result', result);
  return result;
}

/**
 * 查媒体节点
 * @param {*} startTime 
 * @param {*} endTime 
 * @param {*} appid 
 * @param {*} roomid 
 * @param {*} streamID 
 * @returns 
 */
function generateMediaNodePath(startTime, endTime, appid, roomid, streamID) {
  return `https://logcenter-new.zego.cloud/app/discover#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:'${startTime}',to:'${endTime}'))&_a=(columns:!(action,content,event,userid,client_time,action_detail,client_ip,ipip.country_name,ipip.city_name,ipip.region_name),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'4f890960-f021-11eb-b67b-a151f09c199f',key:roomid,negate:!f,params:(query:'${roomid}'),type:phrase),query:(match_phrase:(roomid:'${roomid}'))),('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'4f890960-f021-11eb-b67b-a151f09c199f',key:appid,negate:!f,params:(query:${appid}),type:phrase),query:(match_phrase:(appid:${appid})))),index:'4f890960-f021-11eb-b67b-a151f09c199f',interval:auto,query:(language:lucene,query:'(%22${streamID}%22%20AND%20%22sdp%22%20AND%20%22zc.s.bwh%22)'),sort:!(!('@timestamp',asc)))`;
}

/**
 * 生成UDP
 * @param {*} startTime 
 * @param {*} endTime 
 * @param {*} appid 
 * @param {*} streamID 
 */
function generateUDPPath(startTime, endTime, appid, streamID) {

  let s = encodeURI(new Date(startTime).format());
  let e = encodeURI(new Date(endTime).format());
  console.error(s, e)
  return `https://boss.zego.cloud/qualityOperate/DataDetail/UdpPackage?start_time=${s}&end_time=${e}&stream=${streamID}&server_ip=&server_port=&kind=&node_class=&src_type=&app_id=${appid}&src_ip=&width=&height=&sdn=&ap=`;
}

Date.prototype.format = function (format) {
  if ((format = "" || format == undefined)) {
    format = "yyyy/mm/dd h:m:s"
  }
  let conf = ['yyyy', 'mm', 'dd', 'h', 'm', 's', 'S'];
  let arr = {
    'yyyy': this.getFullYear(),
    'mm': this.getMonth() + 1,
    'dd': this.getDate(),
    'h': this.getHours(),
    'm': this.getMinutes(),
    's': this.getSeconds(),
    'S': this.getMilliseconds(),
  };
  conf.forEach(function (item) {
    format = format.replace(item, arr[item])
  });
  return format;
};

function generateSwitchDevicePath(startTime, endTime, appid, roomid) {
  return `https://logcenter-new.zego.cloud/app/discover#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:'${startTime}',to:'${endTime}'))&_a=(columns:!(action,event,id_name,device_id,device),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'4f890960-f021-11eb-b67b-a151f09c199f',key:appid,negate:!f,params:(query:${appid}),type:phrase),query:(match_phrase:(appid:${appid}))),('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'1fcbafa0-6651-11ed-a87e-3da84820e0b7',key:room_id,negate:!f,params:(query:'${roomid}'),type:phrase),query:(match_phrase:(room_id:'${roomid}')))),index:'1fcbafa0-6651-11ed-a87e-3da84820e0b7',interval:auto,query:(language:lucene,query:'%22%2Fsdk%2Flogin%22%20OR%20%22%2Fdevice%2Fapi%2Faudio_c%22%20OR%20%22%2Fdevice%2Fapi%2Fvideo_c%22'),sort:!(!('@timestamp',asc)))`;
}
// 上传数据
document.getElementById('upload').addEventListener('change', handleFile);

function handleFile(e) {
  const file = e.target.files[0];
  if (!file) return;
  const reader = new FileReader();

  reader.onload = function (e) {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, {
      type: 'array'
    });
    const sheetName = workbook.SheetNames[0];
    const sheet = workbook.Sheets[sheetName];
    const rows = XLSX.utils.sheet_to_json(sheet, {
      header: 1,
      raw: false
    });

    if (rows.length === 0) {
      alert("No data found in the sheet.");
      return;
    }

    // Set headers from the first row
    headers = rows[0];
    startTimeIndex=headers.indexOf("start_time");
    let output = headers.join('\t') + '\n'; // Add header to output
    const jsonOutput = [];
    roomIdData = {}; // Initialize roomIdData object

    rows.slice(1).forEach(row => { // Skip header row
      // Handle date/time conversion
      let date = row[0];
      if (typeof date === 'object' && date instanceof Date) {
        date = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}, ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
      } else {
        date = row[0];
      }

      // Format the rest of the row
      const formattedRow = row.map(cell => cell !== undefined ? cell.toString() : '').join('\t');
      output += formattedRow + '\n';

      // Add row data to JSON output
      jsonOutput.push(row.reduce((acc, value, index) => {
        acc[headers[index]] = value;
        return acc;
      }, {}));

      // Add formatted data to roomIdData object
      const roomId = row[headers.indexOf("room_id")];
      if (!roomIdData[roomId]) {
        roomIdData[roomId] = [];
      }
      roomIdData[roomId].push(formattedRow);
    });
    console.log('jsonOutput', jsonOutput)
    const roomIds = jsonOutput.map(item => item.room_id.replace(/[,]/g, ''));
    const result = roomIds.join(',');
    console.log('result', result)
    renderExcelData(jsonOutput)
  };

  reader.readAsArrayBuffer(file);
}
//渲染表格
function renderExcelData(data) {
  // 按owner分组数据
  const groupedData = data.reduce((acc, item) => {
    if (!acc[item.owner]) {
      acc[item.owner] = [];
    }
    acc[item.owner].push(item);
    return acc;
  }, {});

  let lastClickedLink = null; // 用于存储最后一次点击的链接

  // 生成HTML结构并赋予点击事件
  const ownersDiv = document.getElementById('owners');
  const outputDiv = document.getElementById('output');

  for (const [owner, rooms] of Object.entries(groupedData)) {
    const ownerRow = document.createElement('div');
    ownerRow.className = 'owner-row';

    const ownerName = document.createElement('span');
    ownerName.className = 'owner-name';
    ownerName.textContent = `${owner}:`;
    ownerRow.appendChild(ownerName);

    rooms.forEach((room, index) => {
      const roomLink = document.createElement('a');
      roomLink.href = "#";
      roomLink.className = 'room-link';
      roomLink.textContent = `房间号 ${rooms[index].room_id},`;
      roomLink.dataset.roomInfo = JSON.stringify(room);
      roomLink.addEventListener('click', function (event) {
        event.preventDefault();

        // 取消上一次点击链接的激活状态
        if (lastClickedLink) {
          lastClickedLink.classList.remove('active');
        }

        // 设置当前点击链接的激活状态
        this.classList.add('active');
        lastClickedLink = this; // 更新最后点击的链接

        const roomInfo = JSON.parse(this.dataset.roomInfo);
        outputDiv.textContent = `Room Info: ${JSON.stringify(roomInfo, null, 2)}`;
        onGeneratePathByExecl(roomInfo.room_id)
      });
      ownerRow.appendChild(roomLink);
    });

    ownersDiv.appendChild(ownerRow);
  }

}

function onGeneratePathByExecl(roomId) {
  questionStr = getStrByRoomId(roomId)
  onGeneratePath();
}

function getStrByRoomId(roomId) {
  const result = roomIdData[roomId] || ['No data found for this Room ID'];
  return result.join('\n');
}